#!/bin/bash


function proc_number(){
    proc_number=$(ps -ef | grep "drama" | grep -v "grep " | grep -v "vim " | grep -v "vi "|grep -v "tail" | grep -v "util.sh"|grep -v ".sh"  |grep -v "bash"| awk '{print $2}' | wc -l)
    echo "$proc_number"
}


function proc_pid(){
    proc_pid=$(ps -ef | grep "drama" | grep -v "grep " | grep -v "vim " | grep -v "vi "|grep -v "tail" | grep -v "util.sh"|grep -v ".sh" |grep -v "bash"| awk '{print $2}')
    echo "$proc_pid"
}

function start(){
	if [ $(proc_number) -eq 0 ];then
		echo "drama not running"
		echo "start drama..."
		nohup ./drama nohup.out 2>&1 &
		if [ $(proc_number) -eq 0 ];then
			echo "start failed .... please check nohup.out 日志文件"
		else
			echo "successful. PID:$(proc_pid)"
		fi
	else
		echo "PID:$(proc_pid)"
		echo "already running ..."
	fi
}

function stop(){
	if [ $(proc_number) -eq 0 ];then
		echo "not running"
	else
		kill $(proc_pid)
                a=0
                while [ $a -lt 200 ]
                do
                   sleep 0.1
                   if [ $(proc_number) -eq 0 ];then
                        echo "process stop sucessfull"
                        break
                   else
                        let a++
                        echo "killing process,check is exist, try again $a count"
                        if [ $a -eq 200 ];then
                           if [ $(proc_number) -eq 0 ];then
                              echo "process stop sucessfull"
                           else
                              echo "================process stop faild============="
                           fi
                           break
                        fi
                   fi
                done
	fi
}

case "$1" in
	start)
	start
	exit;
		;;
	stop)

	stop
	exit;
		;;
	restart)
        stop
        start
	exit;
                ;;
	*)
	echo "Input not ok"
	echo "Usage: sh  $0  start ||  stop"
esac
exit